package com.csis.framework.util.jqgrid;

import java.lang.reflect.Field;

/**
 * default {@link JqGridResponseFilter}, use reflect entity field;
 * 
 * @author dailey
 * 
 * @param <E>
 *            entity class type
 */
public class DefaultJqGridResponseFilter<E> implements JqGridResponseFilter<E> {

	@Override
	public Object[] getJqGridCell(Cell<E> e) {
		Field[] fields = e.getEntityClass().getDeclaredFields();
		//add sequence to the first result array
		Object[] objs = new Object[fields.length+1];
		objs[0]=e.getSequence();
		for (int i = 0; i < fields.length; i++) {
			fields[i].setAccessible(true);
			try {
				objs[i] = fields[i].get(e.getEntity());
				objs[i] = (objs[i] == null ? "" : objs[i]);
			} catch (Exception ex) {
				objs[i] = "";
			}
		}
		return objs;
	}

	@Override
	public Object getJqGridCellId(Cell<E> e) {
		Object obj = null;
		Field[] fields = e.getEntityClass().getDeclaredFields();
		fields[0].setAccessible(true);
		try {
			obj = fields[0].get(e.getEntity());
			obj = (obj == null ? "" : obj);
		} catch (Exception ex) {
			obj = "";
		}
		return obj;
	}

}
